import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import okhttp3.*;

import java.io.IOException;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

public class test {
    private static final Integer TIME_OUT = 5 * 60; // 5 minutes timeout
    private static final OkHttpClient client = new OkHttpClient.Builder()
            .connectTimeout(TIME_OUT, TimeUnit.SECONDS)  // Set connection timeout
            .readTimeout(TIME_OUT, TimeUnit.SECONDS)     // Set read timeout
            .build();

    public static void main(String[] args) {
        // 1. 构建 JSON 请求体
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        String userMessage = "报案人姓名张三报案人电话11111111111报案人车牌号闽a55789对方姓名李四对方电话22222222222对方车牌号粤a12345事故时间今天人员受伤李四死亡，张三逃逸事故描述双方时速200码事故现场处理建议无";
        JsonObject requestBody = new JsonObject();
        requestBody.addProperty("bot_id", "7494115670842425353");
        requestBody.addProperty("user_id", "7494114316342460452");

        JsonArray additionalMessages = new JsonArray();

        // 创建 additional_messages 中的对象
        JsonObject message = new JsonObject();
        message.addProperty("role", "user");
        message.addProperty("content", userMessage);  // 动态插入 content
        message.addProperty("content_type", "text");

        // 将 message 添加到 additionalMessages 数组
        additionalMessages.add(message);

        // 将 additionalMessages 添加到 requestBody
        requestBody.add("additional_messages", additionalMessages);
        String s = requestBody.toString();
        RequestBody body = RequestBody.create(s, JSON);

        // 2. 创建 Request
        Request request = new Request.Builder()
                .url("https://api.coze.cn/v3/chat")
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Authorization", "Bearer pat_dq1fzqAo8XQijKiKutrVsfFsQiWlOgntZ5WmBhJByYquTuVShnbsyxy8BiRkeiMo")
                .build();

        // 3. 发送请求并处理响应
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                System.err.println("Request failed: " + response);
                return; // Exit early on failure
            }

            String temp = response.body() != null ? response.body().string() : "";
            if (temp.isEmpty()) {
                System.err.println("Received empty response body.");
                return; // Exit early if body is empty
            }

            System.out.println("Response: " + temp);
            JsonObject jsonObject = JsonParser.parseString(temp).getAsJsonObject();

            // 获取嵌套的 data 对象
            JsonObject data = jsonObject.getAsJsonObject("data");
            if (data == null) {
                System.err.println("Data field is missing.");
                return;
            }

            String id = data.has("id") ? data.get("id").getAsString() : null;
            String conversationId = data.has("conversation_id") ? data.get("conversation_id").getAsString() : null;

            if (id == null || conversationId == null) {
                System.err.println("Missing required fields: id or conversation_id.");
                return;
            }

            while (true) {
                Thread.sleep(1000); // Pause for 1 second before retrying

                // Send retrieve request
                Request request1 = new Request.Builder()
                        .url("https://api.coze.cn/v3/chat/retrieve?conversation_id=" + conversationId + "&chat_id=" + id)
                        .get()
                        .addHeader("Content-Type", "application/json")
                        .addHeader("Authorization", "Bearer pat_dq1fzqAo8XQijKiKutrVsfFsQiWlOgntZ5WmBhJByYquTuVShnbsyxy8BiRkeiMo")
                        .build();

                try (Response response1 = client.newCall(request1).execute()) {
                    if (!response1.isSuccessful()) {
                        System.err.println("Retrieve request failed: " + response1);
                        break;
                    }

                    temp = response1.body() != null ? response1.body().string() : "";
                    if (temp.isEmpty()) {
                        System.err.println("Empty response on retrieve request.");
                        break;
                    }

                    JsonObject jsonObject1 = JsonParser.parseString(temp).getAsJsonObject();

                    data = jsonObject1.getAsJsonObject("data");
                    String status = data != null && data.has("status") ? data.get("status").getAsString() : null;

                    if ("completed".equals(status)) {
                        break;
                    }
                } catch (IOException e) {
                    System.err.println("Error during retrieve request: " + e.getMessage());
                    break;
                }
            }

            // Send message list request
            Request listRequest = new Request.Builder()
                    .url("https://api.coze.cn/v3/chat/message/list?conversation_id=" + conversationId + "&chat_id=" + id)
                    .get()
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Authorization", "Bearer pat_dq1fzqAo8XQijKiKutrVsfFsQiWlOgntZ5WmBhJByYquTuVShnbsyxy8BiRkeiMo")
                    .build();

            try (Response response1 = client.newCall(listRequest).execute()) {
                if (!response1.isSuccessful()) {
                    System.err.println("Message list request failed: " + response1);
                    return;
                }

                temp = response1.body() != null ? response1.body().string() : "";
                if (temp.isEmpty()) {
                    System.err.println("Empty response on message list request.");
                    return;
                }

                System.out.println("Message List Response: " + temp);
                jsonObject = JsonParser.parseString(temp).getAsJsonObject();

                JsonArray dataArray = jsonObject.has("data") ? jsonObject.getAsJsonArray("data") : new JsonArray();

                StringBuilder contentBuilder = new StringBuilder();
                for (int i = 0; i < dataArray.size(); i++) {
                    JsonObject item = dataArray.get(i).getAsJsonObject();
                    if (item.has("content")) {
                        contentBuilder.append(item.get("content").getAsString()).append(" ");
                    }
                }

                String concatenatedContent = contentBuilder.toString().trim();
                System.out.println("Concatenated Content: " + concatenatedContent);
            } catch (IOException e) {
                System.err.println("Error during message list request: " + e.getMessage());
            }

        } catch (IOException | InterruptedException e) {
            System.err.println("Request failed: " + e.getMessage());
        }
    }
}
